package com.frontop.terminal.rmonclient.worker;


import com.frontop.terminal.rmonclient.client.Client;
import com.frontop.terminal.rmonclient.protocol.Command;
import com.frontop.terminal.rmonclient.protocol.Packet;
import com.frontop.terminal.rmonclient.util.Log;

import java.io.File;
import java.io.FileInputStream;

/**
 * @author matrixy 优化：ccc
 * @date 2018/5/15 2021/6/4
 */
public class FileTransferWorker extends BaseWorker {
    File file;
    Client clientSession;

    public FileTransferWorker(Client clientSession, File file) {
        this.file = file;
        this.clientSession = clientSession;
    }

    private void transfer() throws Exception {
        int len;
        byte[] block = new byte[40960];
        try (FileInputStream fis = new FileInputStream(this.file)) {
            while ((len = fis.read(block)) > -1) {
                byte[] data;
                if (len == 40960) {
                    data = block;
                } else {
                    data = new byte[len];
                    System.arraycopy(block, 0, data, 0, len);
                }
                clientSession.send(Packet.create(Command.DOWNLOAD_FILE_RESPONSE, len + 4).addInt(len).addBytes(data));
            }
            clientSession.send(Packet.create(Command.DOWNLOAD_FILE_RESPONSE, 4).addInt(0));
        }
    }

    @Override
    public void run() {
        try {
            transfer();
        } catch (Exception e) {
            Log.error(e);
        }
    }
}
